package com.zed.api.common.param;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 支持初始化参数的配置项
 *
 * @author Zed
 */
public class DefaultParamsConfig implements Parameters {

    private Map<String, Object> params;

    protected DefaultParamsConfig() {

    }

    public DefaultParamsConfig(Map<String, Object> params) {
        this.params = params == null ?
                Collections.emptyMap() :
                Collections.unmodifiableMap(params);
    }

    /**
     * 构造方法
     *
     * @param builder {@link ParamsBuilder}
     */
    public DefaultParamsConfig(ParamsBuilder builder) {
        this.params = builder.params == null ?
                Collections.emptyMap() :
                Collections.unmodifiableMap(builder.params);
    }

    @Override
    public Object getParameter(String name) {
        return this.params.get(name);
    }

    @Override
    public <T> T getParameter(String name, Class<T> requireClazz) {

        Object result = this.getParameter(name);

        if (requireClazz != null && result != null) {
            if (requireClazz.isAssignableFrom(result.getClass())) {
                return requireClazz.cast(result);
            }
        }

        return null;
    }

    @Override
    public List<String> getParameterNames() {
        return new ArrayList<>(this.params.keySet());
    }

    @Override
    public List<String> getParameterNames(String prefix) {
        return this.params.keySet().stream()
                .filter(name -> name.startsWith(prefix))
                .collect(Collectors.toList());
    }


}
